package com.ciwong.epaper.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.ocr.sdk.OCR;
import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.CheckFloatPermissionBean;
import com.ciwong.epaper.common.EVariableGlobal;
import com.ciwong.epaper.common.db.DatabaseHelper;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.bean.Service;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.ui.BookDeskParentFragment;
import com.ciwong.epaper.modules.me.ui.FindFragment;
import com.ciwong.epaper.modules.me.ui.MeFragment;
import com.ciwong.epaper.modules.me.ui.WorkFragment;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.ZipPackageUtils;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.eyeguard.EyeGuardModeView;
import com.ciwong.mobilelib.eyeguard.permission.FloatWindowManager;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseActivityManager;
import com.ciwong.mobilelib.utils.CWUpdate;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.ciwong.mobilelib.widget.CWDialog;
import com.tencent.connect.common.Constants;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants.JUMP_2_ACTIVITY_FLAG;
import static com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants.JUMP_2_ACTIVITY_FLAG_BOOK_DESK;
import static com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants.JUMP_2_ACTIVITY_FLAG_HOMEWORK;
import static com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants.JUMP_2_ACTIVITY_FLAG_ME_FRAGEENT;


/**
 * Created by RES-KUNZHU on 2015/7/24.
 */
public class MainActivity extends BaseActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final int HOME_WORK_INDEX = 0;
    public static final int BOOK_DESK_INDEX = 1;
    public static final int FIND_INDEX = 2;
    public static final int WO_INDEX = 3;

    private EApplication mNApplication;
    private LinearLayout tabContainer;
    public static Fragment curFragment;
    private FragmentManager fragmentManager;
    private FragmentTransaction ft;
    // fragment列表
    private List<Fragment> fragments = new ArrayList<Fragment>();
    private TextView mTvHomework, mTvBookDesk, mTvWo, mTvFind;
    private ImageView tab_img_homework, tab_img_me, tab_img_bookdesk, tab_img_find;
    private View btn_homework, btn_find, btn_book_desk, btn_tab_me;

    public static final int JUMP_SORECE_TYPE_LSW = 101;
    public static final int JUMP_SORECE_TYPE_ME_SETTING = 102;
    public static final int JUMP_SORECE_TYPE_MY_BOOKS = 103;
    private int sourceType = JUMP_SORECE_TYPE_MY_BOOKS;
    private Handler mHandler = new Handler();
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int i = v.getId();
            if (i == R.id.main_tab1) {
                if (!EVariableGlobal.CHECKED_GUIDE_DIALOG_SHOWING)
                    setTab(HOME_WORK_INDEX);
            } else if (i == R.id.main_tab2) {
                setTab(BOOK_DESK_INDEX);
            } else if (i == R.id.main_tab3) {
                setTab(FIND_INDEX);
            } else if (i == R.id.main_tab4) {
                if (!EVariableGlobal.CHECKED_GUIDE_DIALOG_SHOWING)
                    setTab(WO_INDEX);
            }
        }
    };
    private String mAppwidgetWorkId = null;


    @Override
    protected int setView() {
        return R.layout.activity_main;
    }

    @Override
    protected void preCreate() {
        super.preCreate();
        mNApplication = (EApplication) getApplication();
        mNApplication.initAppData();

        // 通过该接口可以控制敏感数据采集，true表示可以采集，false表示不可以采集，
        // 该方法一定要最优先调用，请在StatService.autoTrace(Context context)
        // 之前调用，采集这些数据可以帮助App运营人员更好的监控App的使用情况，
        // 建议有用户隐私策略弹窗的App，用户未同意前设置false,同意之后设置true
//        StatService.setAuthorizedState(this, true);
    }

    @Override
    protected void findViews() {
        tabContainer = (LinearLayout) findViewById(R.id.main_tab_container);
        mTvHomework = (TextView) findViewById(R.id.tv_homework);
        mTvBookDesk = (TextView) findViewById(R.id.tv_book_desk);
        mTvFind = (TextView) findViewById(R.id.tv_find);
        mTvWo = (TextView) findViewById(R.id.tv_wo);

        tab_img_homework = (ImageView) findViewById(R.id.tab_img_homework);
        tab_img_bookdesk = (ImageView) findViewById(R.id.tab_img_bookdesk);
        tab_img_find = (ImageView) findViewById(R.id.tab_img_find);
        tab_img_me = (ImageView) findViewById(R.id.tab_img_me);


        btn_homework = findViewById(R.id.btn_homework);
        btn_book_desk = findViewById(R.id.btn_book_desk);
        btn_find = findViewById(R.id.btn_find);
        btn_tab_me = findViewById(R.id.btn_tab_me);

    }

    /**
     * 获取当前Fragment
     *
     * @return
     */
    public Fragment getCurFragment() {
        return curFragment;
    }

    @Override
    protected void init() {
        registStatistics(true);
        if (!ImageLoaderHelper.getInstance().isInited()) {
            ImageLoaderHelper.getInstance().init(getApplicationContext());
        }
        setValideSource(false);
        hideTitleBar();
        BaseActivityManager.getInstance().setMainActivity(this);
        fragmentManager = getSupportFragmentManager();
        fragments.add(WorkFragment.newInstance());
        fragments.add(BookDeskParentFragment.newInstance());
        fragments.add(FindFragment.newInstance());
        fragments.add(MeFragment.newInstance());

        ft = fragmentManager.beginTransaction();
        ft.add(R.id.main_content, fragments.get(HOME_WORK_INDEX));
        ft.add(R.id.main_content, fragments.get(BOOK_DESK_INDEX));
        ft.add(R.id.main_content, fragments.get(FIND_INDEX));
        ft.add(R.id.main_content, fragments.get(WO_INDEX));
        //curFragment = fragments.get(H_INDEX);
        //根据产品需求将进入首次展示的页面为书柜 更改与20160709  by young
        getServiceState();
        //引导页面跳到学习设置
        sourceType = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SETTING_JUMP_SOURCE, JUMP_SORECE_TYPE_MY_BOOKS);
        if (JUMP_SORECE_TYPE_LSW == sourceType) {
            curFragment = fragments.get(WO_INDEX);
            ft.hide(fragments.get(HOME_WORK_INDEX));
            ft.hide(fragments.get(BOOK_DESK_INDEX));
            ft.hide(fragments.get(FIND_INDEX));
            ft.show(fragments.get(WO_INDEX));
            ft.commitAllowingStateLoss();
            setSelect(WO_INDEX);

        } else if (JUMP_SORECE_TYPE_MY_BOOKS == sourceType) {
            curFragment = fragments.get(BOOK_DESK_INDEX);
            ft.hide(fragments.get(HOME_WORK_INDEX));
            ft.show(fragments.get(BOOK_DESK_INDEX));
            ft.hide(fragments.get(FIND_INDEX));
            ft.hide(fragments.get(WO_INDEX));
            ft.commitAllowingStateLoss();
            setSelect(BOOK_DESK_INDEX);
        } else {
            curFragment = fragments.get(HOME_WORK_INDEX);
            ft.show(fragments.get(HOME_WORK_INDEX));
            ft.hide(fragments.get(BOOK_DESK_INDEX));
            ft.hide(fragments.get(FIND_INDEX));
            CWLog.d(TAG, TAG + "init");
            ft.hide(fragments.get(WO_INDEX));
            ft.commitAllowingStateLoss();
            setSelect(HOME_WORK_INDEX);

            /*curFragment = fragments.get(BS_INDEX);
            ft.hide(fragments.get(H_INDEX));
            ft.show(fragments.get(BS_INDEX));
            ft.hide(fragments.get(WO_INDEX));
            ft.commitAllowingStateLoss();
            setSelect(BS_INDEX);*/
        }

        IntentFilter myIntentFilter = new IntentFilter();

        myIntentFilter.addAction(EpaperConstant.BROADCAST_CLASS_CHANGE);

        myIntentFilter.addAction(EpaperConstant.BROADCAST_HIDE_TAB_BAR);

        myIntentFilter.addAction(EpaperConstant.BROADCAST_SHOW_TAB_BAR);
        myIntentFilter.addAction(LoginToken.ACTION_EXIT_LOGIN);

        registerReceiver(mMainBroadcastReceiver, myIntentFilter);
        //获取离线下载包
        ZipPackageUtils.checkHtmlFileNeedDownload(this, null);

//        copyHtmlFile();
        //设置护眼模式
        final UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
        if (userInfoBase != null) {
            boolean isEyeGuardMode = ESystem.getSharedBoolean(MeFragment.IS_USE_EYE_GUARD_MODE + userInfoBase.getUserId(), false);
            if (isEyeGuardMode) {
                FloatWindowManager.getInstance().setOnFloatWindowPerssionGrantListener(new FloatWindowManager.OnFloatWindowPerssionGrantListener() {
                    @Override
                    public void onPerssionGranted() {
                        EyeGuardModeView.showEyeGuard(true);
                        EApplication.getInstance().isEyeGuardModeOpen = true;
                        BaseApplication.getInstance().isEyeGuardPerssionGet = true;
                    }

                    @Override
                    public void onGotoGetPerssion() {

                    }

                    @Override
                    public void onPerssionNoGranted() {
                        EApplication.getInstance().isEyeGuardModeOpen = false;
                        BaseApplication.getInstance().isEyeGuardPerssionGet = false;
                        ESystem.setSharedBoolean(MeFragment.IS_USE_EYE_GUARD_MODE + userInfoBase.getUserId(), false);
                    }

                    @Override
                    public void onClickCheckSetMethod() {

                    }
                }).applyOrShowFloatWindowOnlyCheckPerssion(MainActivity.this);
            }


        }
        initWoordBookDB();
        initAppWidgetIntent();
        String mPlayerspeed = ESystem.getSharedString("mPlayerspeed" + userInfoBase.getUserId(), "1.0");
        EApplication.getInstance().mPlayerspeed = Float.parseFloat(mPlayerspeed);
        int mFontSizeScale = 1;
        try {
            mFontSizeScale = ESystem.getSharedInt("xixi:fontSizeScale", 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EApplication.getInstance().mFontSizeScale = mFontSizeScale;
    }

    private void initWoordBookDB() {
        long userId = -1;
        if (getUserInfoBase() != null) {
            userId = getUserInfoBase().getUserId();
        }
        DatabaseHelper.initDatabase(getApplicationContext(), userId);
    }

    @Override
    protected void onResume() {
        CWLog.d(TAG, TAG + "mainactivity_--onResume");
        checkUpdate();
        super.onResume();
        WxShareHelper.getInstance().onResumeResultData();
        //刷新vip 信息
        ((MeFragment) fragments.get(WO_INDEX)).setMemberInfo(false);


        //如果是从模考页面引导过来，弹出学习设置
        if (JUMP_SORECE_TYPE_LSW == sourceType) {
            final MeFragment meFragment = (MeFragment) fragments.get(WO_INDEX);
            meFragment.dampScrollView.post(new Runnable() {
                public void run() {
                    meFragment.dampScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    meFragment.showStudySettingDialog();
                }
            });

        }
        sourceType = 0;
//        ViedoJumpManager.jumpToKHBVideoPlayActivity(0, 0, MainActivity.this, "/storage/emulated/0/ciwong/newspaper/dubing/video/400d9ad501a3459572091acb44fe9028");

//        String soundUrl = "/storage/emulated/0/ciwong/newspaper/dubing/video/test01.mp3";
//        AudioPlayer.getInstance().setOnPlayListener(new OnPlayListener() {
//            @Override
//            public void onReadPlayer(long l, Object o) {
//                CWLog.e("byou", "onReadPlayer:l=" + l + "---l1=" + o.toString());
//            }
//
//            @Override
//            public void onPlayStart(Object o) {
//
//            }
//
//            @Override
//            public void stop(Object o) {
//            }
//
//            @Override
//            public void onError(int i, Object o) {
//            }
//
//            @Override
//            public void onBuffer(Object o, long l, long l1) {
//                CWLog.e("byou", "onBuffer:l=" + l + "---l1=" + l1);
//            }
//
//            @Override
//            public void onPlaying(long l, long l1) {
//                CWLog.e("byou", "onPlaying:l=" + l + "---l1=" + l1);
//            }
//        }).play(BaseConstants.FILE_PREFIX + soundUrl, soundUrl);

        //获取imsi地址
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
//        } else {
//            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//            Log.e("byou", telephonyManager.toString());
//            int simState = telephonyManager.getSimState();
//            Log.e("byou", simState + "");
//            if (simState == TelephonyManager.SIM_STATE_READY) {
//                String imsi = telephonyManager.getSubscriberId();
//                String iccid = telephonyManager.getSimSerialNumber();
//                String simiName = telephonyManager.getSimOperatorName();
//                Log.e("byou", "simiName=" + simiName);
//                Log.e("byou", "imsi=" + imsi);
//                Log.e("byou", "iccid=" + iccid);
//            }
//        }
    }

    /**
     * Appwidget跳进来处理
     */
    private void initAppWidgetIntent() {
        int checkFlag = JUMP_2_ACTIVITY_FLAG_HOMEWORK;//默认选择作业页面
        Intent intent = getIntent();
        int intExtra = intent.getIntExtra(JUMP_2_ACTIVITY_FLAG, checkFlag);
        if (intExtra == JUMP_2_ACTIVITY_FLAG_HOMEWORK) {//跳转作业界面
            Bundle extras = intent.getExtras();
            if (extras != null) {
                mAppwidgetWorkId = extras.getString(AppWidgetConstants.WIDGET_HOMEWORK_ITEM_DATA);
                System.out.println("lzh extras appwidgetWorkId : " + mAppwidgetWorkId);
            }
        } else if (intExtra == JUMP_2_ACTIVITY_FLAG_BOOK_DESK) {//跳转桌面
            findViewById(R.id.main_tab2).performClick();
        } else if (intExtra == JUMP_2_ACTIVITY_FLAG_ME_FRAGEENT) {//跳转我的页面
            findViewById(R.id.main_tab4).performClick();
        }
    }

    //获取作业条目的doworkid
    public String getAppwidgetWorkId() {
        return mAppwidgetWorkId;
    }

    public void setAppwidgetWorkId(String appwidgetWorkId) {
        mAppwidgetWorkId = appwidgetWorkId;
    }


    @Override
    protected void initEvent() {
        findViewById(R.id.main_tab1).setOnClickListener(mOnClickListener);
        findViewById(R.id.main_tab2).setOnClickListener(mOnClickListener);
        findViewById(R.id.main_tab3).setOnClickListener(mOnClickListener);
        findViewById(R.id.main_tab4).setOnClickListener(mOnClickListener);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void loadData() {
        CWSys.setSharedBoolean(EConstants.SHARE_KEY_AUTO_LOGIN, true);
//        sendUserPushId();
//        sendTestPushId();//开发时设置的别名，平时不用。
//        checkUpdate();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        CWLog.e("TAT", "【MainActivity】---onDestroy");
        BaseActivityManager.getInstance().setMainActivity(null);
        EventBus.getDefault().unregister(this);
        //设置本ID非首次登录
        CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_FIRST_LOGIN + SerializableManager.getInstance().getUserId(true), false);
        unregisterReceiver(mMainBroadcastReceiver);
        // 释放内存资源
        OCR.getInstance(getApplicationContext()).release();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(getClass().getName(), "---------onKeyDown--------");
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (JUMP_SORECE_TYPE_LSW != sourceType && JUMP_SORECE_TYPE_MY_BOOKS != sourceType) {
                moveTaskToBack(true);
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE) {
            QQShareHelper.getInstance().onActivityResultData(requestCode, resultCode, data);
        } else if (requestCode == RequestCode.BookDeskResquestCode.REQ_CODE_TO_ADD_BOOK_FROM_BOOK_DESK) {
            if (resultCode == RESULT_OK) {
                setTab(BOOK_DESK_INDEX);
            }
        } else if (resultCode == RESULT_OK) {
            if (requestCode == MeFragment.REQUEST_CODE_CAMERA || requestCode == MeFragment.REQUEST_CODE_ALBUM || requestCode == MeFragment.REQUEST_CODE_CROP_CAMERA || requestCode == MeFragment.REQUEST_CODE_CROP_ALBUM || requestCode == MeFragment.REQUEST_CODE_TO_MODIFY_USER_INFO) {
                fragments.get(WO_INDEX).onActivityResult(requestCode, resultCode, data);
                return;
            }
            switch (requestCode) {
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_CHANGE_NEWSPAPER_BRAND:
                    break;

                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY:
//                    ((EpaperFragment) fragments.get(DZB_INDEX)).setMemberInfo();
                    ((MeFragment) fragments.get(WO_INDEX)).setMemberInfo(false);
//                    ((HomeWorkFragment) fragments.get(H_INDEX)).getBookBooksFromNet();
                    break;
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_SETTING:
//                    finish();
                    break;
                case RequestCode.AddBookActivityResquestCode.REQ_CODE_JUMP_TO_SERVICE_LIST:
                    Service service = null;
                    if (data != null) {
                        service = (Service) data.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
                    }
                    setTab(BOOK_DESK_INDEX);
                    if (null != service) {
                        Log.d("ciwong", "#####service.getId()##########" + service.getId());
                        EpaperJumpManager.jumpToAddBookAndService(R.string.go_back, MainActivity.this, service);
                    }
                    break;
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK:
                    break;
                case CWUpdate.CODE_REQUEST_WRITESD_PERMISSION:
                    checkUpdate();
                    break;
                case RequestCode.HomeWorkFragmentResquestCode.QEQ_FOR_HOME_WORK_MSG:
                    switchMainOval(false);
                    break;
                default:
                    break;
            }
        } else if (requestCode == RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_WORK_LIST
                && resultCode == RESULT_CANCELED) {
            switchMainOval(false);
        } else if (requestCode == RequestCode.HomeWorkFragmentResquestCode.QEQ_FOR_HOME_WORK_MSG
                && resultCode == RESULT_CANCELED) {
            setTab(HOME_WORK_INDEX);
        }
    }

    /**
     * 获取服务状态
     */
    private void getServiceState() {
        UserInfoBase userInfoBase = mNApplication.getUserInfoBase();

        if (null != userInfoBase) {
            MeDao.getInstance().getServiceDetails(mNApplication,
                    EApplication.BRAND_ID,
                    userInfoBase == null ? 0 : userInfoBase.getUserId(), 0,
                    new BaseExtCallBack(MainActivity.this) {
                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                        }

                        @Override
                        public void failed(Object data) {
                            super.failed(data);
                            DialogUtil.showFailedToastByErrorType(MainActivity.this, data);
                        }

                        //修改于书柜查询服务状态详情 2016/09/11 by young
                        @Override
                        public void success(Object data) {
                            List<ServiceDetail> serviceDetails = (List<ServiceDetail>) data;
                            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST, (Serializable) serviceDetails);
                            EApplication.getInstance().setServiceDetails(serviceDetails);
                            if (null != serviceDetails && serviceDetails.size() > 0) {
                                ServiceDetail mServiceDetail = serviceDetails.get(0);
                                String message = mServiceDetail.getMessage();
                                //是否显示购买弹窗
                                boolean isShowBuyService = false;
                                try {
                                    isShowBuyService = CWSys.getSharedBoolean("isShowBuyService" + CWUtils.getReadTime(System.currentTimeMillis()), false);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (message != null && message.trim().length() > 0 && mServiceDetail.getSurplusData() <= 90) {
                                    if (!isShowBuyService) {
                                        showBuyServiceDialog(message);
                                        CWSys.setSharedBoolean("isShowBuyService" + CWUtils.getReadTime(System.currentTimeMillis()), true);
                                    }
                                }
                            }
                        }
                    });
        }

    }


    private CWDialog showBuyServiceDialog;

    /**
     * 购买vip提示框
     */
    private boolean showBuyServiceDialog(String message) {
        if (showBuyServiceDialog == null) {
            showBuyServiceDialog = new CWDialog(this);
            showBuyServiceDialog.setTitle(R.string.get_permiss_title);
            showBuyServiceDialog.setTitleTextColor(Color.BLACK);
            showBuyServiceDialog.setMessage(message, 16, Color.BLACK, Gravity.LEFT);
            showBuyServiceDialog.setPositiveButton(R.string.go_bu_service_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //拓展服务
                    MeJumpManager.jumpToResourseCenterH5Activity(MainActivity.this, R.string.go_back, getResources().getString(R.string.resource_center));
                    showBuyServiceDialog.dismiss();
                }
            });
            showBuyServiceDialog.setNegativeButton(R.string.go_bu_service_no, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showBuyServiceDialog.dismiss();
                }
            });
        }
        showBuyServiceDialog.show();
        return true;
    }

    /**
     * 设置选中TAB
     *
     * @param currentIndex 选中TAB下标
     */
    public void setSelect(int currentIndex) {
        // 启动动画
        switch (currentIndex) {
            case HOME_WORK_INDEX:
                mTvHomework.setSelected(true);
                mTvBookDesk.setSelected(false);
                mTvFind.setSelected(false);
                mTvWo.setSelected(false);
                tab_img_homework.setImageResource(R.mipmap.main_tab_homework_press);
                tab_img_bookdesk.setImageResource(R.mipmap.main_tab_book_desk_default);
                tab_img_find.setImageResource(R.mipmap.main_tab_find_default);
                tab_img_me.setImageResource(R.mipmap.main_tab_me_default);
                setAnimation(btn_homework);
                break;

            case BOOK_DESK_INDEX:
                mTvHomework.setSelected(false);
                mTvBookDesk.setSelected(true);
                mTvFind.setSelected(false);
                mTvWo.setSelected(false);
                tab_img_homework.setImageResource(R.mipmap.main_tab_homework_default);
                tab_img_bookdesk.setImageResource(R.mipmap.main_tab_book_desk_press);
                tab_img_find.setImageResource(R.mipmap.main_tab_find_default);
                tab_img_me.setImageResource(R.mipmap.main_tab_me_default);
                setAnimation(btn_book_desk);
                break;
            case FIND_INDEX:
                mTvHomework.setSelected(false);
                mTvBookDesk.setSelected(false);
                mTvFind.setSelected(true);
                mTvWo.setSelected(false);
                tab_img_homework.setImageResource(R.mipmap.main_tab_homework_default);
                tab_img_bookdesk.setImageResource(R.mipmap.main_tab_book_desk_default);
                tab_img_find.setImageResource(R.mipmap.main_tab_find_press);
                tab_img_me.setImageResource(R.mipmap.main_tab_me_default);
                setAnimation(btn_find);
                break;
            case WO_INDEX:
                mTvHomework.setSelected(false);
                mTvBookDesk.setSelected(false);
                mTvFind.setSelected(false);
                mTvWo.setSelected(true);
                tab_img_homework.setImageResource(R.mipmap.main_tab_homework_default);
                tab_img_bookdesk.setImageResource(R.mipmap.main_tab_book_desk_default);
                tab_img_find.setImageResource(R.mipmap.main_tab_find_default);
                tab_img_me.setImageResource(R.mipmap.main_tab_me_press);
                setAnimation(btn_tab_me);
                break;
        }
    }


    private void setAnimation(final View view) {
        // 使用AnimationUtils装载动画配置文件
        Animation animation = AnimationUtils.loadAnimation(
                MainActivity.this, R.anim.tab_scale);
        animation.setFillAfter(true);
        final Animation animationShrink = AnimationUtils.loadAnimation(
                MainActivity.this, R.anim.tab_scale_shrink);
        animationShrink.setFillAfter(false);

        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.startAnimation(animationShrink);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        view.startAnimation(animation);
    }

    public void setTab(int index) {
        Fragment fragment;
        if (index == HOME_WORK_INDEX) {
            EVariableGlobal.CHECKED_FRAGMENT_BOOKDESK = false;
            fragment = fragments.get(HOME_WORK_INDEX);
            setSelect(HOME_WORK_INDEX);
        } else if (index == BOOK_DESK_INDEX) {
            EVariableGlobal.CHECKED_FRAGMENT_BOOKDESK = true;
            setSelect(BOOK_DESK_INDEX);
            fragment = fragments.get(BOOK_DESK_INDEX);
        } else if (index == FIND_INDEX) {
            EVariableGlobal.CHECKED_FRAGMENT_BOOKDESK = false;
            fragment = fragments.get(FIND_INDEX);
            setSelect(FIND_INDEX);
        } else if (index == WO_INDEX) {
            EVariableGlobal.CHECKED_FRAGMENT_BOOKDESK = false;
            fragment = fragments.get(WO_INDEX);
            setSelect(WO_INDEX);
        } else {
            EVariableGlobal.CHECKED_FRAGMENT_BOOKDESK = false;
            fragment = null;
        }
        BookDeskParentFragment.newInstance().setUserVisibleHint(EVariableGlobal.CHECKED_FRAGMENT_BOOKDESK);
        if (fragment != null) {
            if (curFragment != null) {
                curFragment.onPause();
            }
            FragmentTransaction ft = fragmentManager.beginTransaction();
            if (fragment.isAdded()) {
                fragment.onResume();
            }
            if (curFragment != null) {
                ft.hide(curFragment);
            }
            ft.show(fragment);
            curFragment = fragment;
            ft.commitAllowingStateLoss();
        }
    }

    /**
     * 显示或隐藏红点
     */
    private void switchMainOval(boolean isShow) {
//        if (mainOvalIV != null) {
//            mainOvalIV.setImageResource(isShow ? R.drawable.shape_oval : 0);
//        }
    }

    /**
     * EventBus监听入口，答案提交状态变化
     *
     * @param answer 用户答案
     */
    public void onEventMainThread(Answer answer) {
        if (answer.getSubmitStatus() != Answer.SubmitStatus.WORK_SUBMITING) {
            switchMainOval(true);
        }
    }


    //检测是否有悬浮框权限
    public void onEventMainThread(CheckFloatPermissionBean checkFloatPermissionBean) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                FloatWindowManager.getInstance().applyOrShowFloatWindowOnlyCheckPerssion(MainActivity.this);
            }
        }, 1500);
    }

    private BaseRequest.VerifyInfo verifyInfo;
    private LoginToken mLoginToken;

    BroadcastReceiver mMainBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (null == intent) {
                return;
            }

            if (EpaperConstant.BROADCAST_CLASS_CHANGE.equals(intent.getAction())) {

                ((MeFragment) fragments.get(WO_INDEX)).setUserInfo();
            } else if (EpaperConstant.BROADCAST_HIDE_TAB_BAR.equals(intent.getAction())) {

                Log.d(TAG, "#####tabContainer.setVisibility(View.GONE)#######");
                tabContainer.setVisibility(View.GONE);

            } else if (EpaperConstant.BROADCAST_SHOW_TAB_BAR.equals(intent.getAction())) {

                Log.d(TAG, "#####tabContainer.setVisibility(View.VISIBLE)#######");
                tabContainer.setVisibility(View.VISIBLE);
            } else if (LoginToken.ACTION_EXIT_LOGIN.equals(intent.getAction())) {
                Log.d(TAG, "#####LoginToken.ACTION_EXIT_LOGIN#######");
                BaseActivityManager.getInstance().killAllActivity();
                finish();
            }

        }
    };


}
